package cn.edu.lit.jsjxy.CourseExample.chapter8;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import cn.edu.lit.jsjxy.CourseExample.R;

public class DatabaseOperationActivity extends AppCompatActivity implements View.OnClickListener
{
    Button btnCreateDatabase, btnDeleteDatabase;
    SQLiteDatabase db;
    final String DB_NAME = "contacts.db";

    String TABLE_NAME = "Users";          //数据表名
    String ID = "_id";                    //ID
    String USER_NAME = "user_name";       //用户名
    String ADDRESS = "address";           //地址
    String TELEPHONE = "telephone";       //联系电话
    String MAIL_ADDRESS = "mail_address"; //电子邮箱

    String sqlStr = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER primary key " +
            "autoincrement, " + USER_NAME + " text not null, " + TELEPHONE + " text not null, " +
            ADDRESS + " text not null, " + MAIL_ADDRESS + " text not null " + ");";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database_operation);

        btnCreateDatabase = findViewById(R.id.btnCreateDatabase);
        btnDeleteDatabase = findViewById(R.id.btnDeleteDatabase);

        btnCreateDatabase.setOnClickListener(this);
        btnDeleteDatabase.setOnClickListener(this);
    }

    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.btnCreateDatabase:
                createDatabase(this);
                break;
            case R.id.btnDeleteDatabase:
                deleteDatabase(this);

                break;
        }
    }

    private void createDatabase(Context context)
    {
        db = context.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
        db.execSQL(sqlStr);


    }

    private void deleteDatabase(Context context)
    {
        context.deleteDatabase(DB_NAME);

    }
}
